package com.life.xxx.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.life.xxx.entity.LifeUser;
import com.life.xxx.mapper.LifeUserMapper;
import com.life.xxx.service.impl.RefreshTokenService;
import com.life.xxx.util.JwtUtil;
import com.life.xxx.util.PasswordUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author: csl
 * @description: 登录注册接口
 * @date: 2025-08-07 15:16
 */
@RestController
@RequestMapping("/user")
public class LoginApi {

    @Autowired
    private LifeUserMapper lifeUserMapper;

    @Autowired
    private RefreshTokenService refreshTokenService;

    /**
     * 用户登录接口
     * @param loginRequest 包含用户名和密码的请求体
     * @return 包含JWT令牌的响应
     */
    @PostMapping("/login")
    public String login(String username,String password ) throws Exception {
        QueryWrapper<LifeUser> lifeUserQueryWrapper = new QueryWrapper<>();
        lifeUserQueryWrapper.eq("user_name",username);
        LifeUser lifeUser = lifeUserMapper.selectOne(lifeUserQueryWrapper);
        if(lifeUser == null){
            return "当前用户不存在";
        }
        boolean isPasswordValid = PasswordUtil.verifyPassword(password, lifeUser.getPassword(), lifeUser.getSalt());
        if(!isPasswordValid){
            return "密码错误";
        }
        String accessToken = JwtUtil.generateAccessToken(lifeUser.getPassword(), lifeUser.getSalt(),lifeUser.getUserId());
        String refreshToken = JwtUtil.generateRefreshToken(lifeUser.getUserId());
        refreshTokenService.save(lifeUser.getUserId(),refreshToken);
        return accessToken;
    }

    /**
     * 用户注册接口
     * @param request 注册请求数据
     * @return 注册结果
     */
    @PostMapping("/register")
    public String register(String username,String password) throws NoSuchAlgorithmException {
        if(username == null || username.trim().isEmpty()){
            return "用户名不能为空";
        }
        if(password == null || password.length() < 6){
            return "密码长度不能少于6位";
        }
        QueryWrapper<LifeUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",username);
        LifeUser lifeUser = lifeUserMapper.selectOne(wrapper);
        if(lifeUser != null){
            return "用户名已存在";
        }

        String salt = PasswordUtil.generateSalt();
        String hashPassword = PasswordUtil.hashPassword(password, salt);

        LifeUser user = new LifeUser();
        user.setUserName(username);
        user.setPassword(hashPassword);
        user.setSalt(salt);
        LocalDateTime localDateTime = LocalDateTime.now();
        user.setCreateTime(localDateTime);
        user.setUpdateTime(localDateTime);
        int insert = lifeUserMapper.insert(user);
        if(insert>0){
            return "注册成功";
        }else {
            return "注册失败：数据库插入失败";
        }
    }

    @PostMapping("/refresh")
    public String refresh(@RequestBody Map<String, String> req) {
        String refreshToken = req.get("refresh_token");
        if (refreshToken == null) {
            return "刷新令牌不存在";
        }

        // 1. 验证 Refresh Token 签名
        String userId = JwtUtil.validateRefreshToken(refreshToken);
        if (userId == null) {
            return "userId解析失败";
        }

        // 2. 检查 Redis 是否存在
        if (!refreshTokenService.isValid(userId, refreshToken)) {
            return "redis不存在";
        }

        // 3. 查询用户（确保用户仍存在）
        LifeUser user = lifeUserMapper.selectById(userId);
        if (user == null) {
            return "用户不存在";
        }

        // 4. 生成新 Access Token
        try {
            String newAccessToken = JwtUtil.generateAccessToken(user.getPassword(), user.getSalt(), userId);
            return newAccessToken;
        } catch (Exception e) {
            return "失败";
        }
    }

    @PostMapping("/logout")
    public String logout(HttpServletRequest request) {
        String userId = (String) request.getAttribute("userId");
        if (userId != null) {
            refreshTokenService.revokeAll(userId);
        }
        return "退出成功";
    }
}
